from flask import Flask, request, render_template_string, redirect, url_for
import pymysql
import os
import logging
import time
from logging.handlers import RotatingFileHandler

app = Flask(__name__)

# 日志配置
def setup_logger():
    log_dir = '/app/logs'
    if not os.path.exists(log_dir):
        os.makedirs(log_dir)
    handler = RotatingFileHandler(
        f'{log_dir}/app.log', maxBytes=10*1024*1024, backupCount=3, encoding='utf-8'
    )
    logging.basicConfig(
        handlers=[handler],
        level=logging.INFO,
        format='%(asctime)s - %(levelname)s - %(message)s'
    )
    # 同时输出到控制台（方便调试）
    console_handler = logging.StreamHandler()
    logging.getLogger().addHandler(console_handler)

# 从环境变量获取MySQL连接信息（严格匹配文档配置）
db_host = os.getenv('DB_HOST', 'db')  # 对应docker-compose中的db服务
db_port = int(os.getenv('DB_PORT', 3306))  # 容器内固定3306
db_user = os.getenv('DB_USER', 'root')
db_password = os.getenv('DB_PASSWORD')  # 必须从环境变量获取，不设默认
db_name = os.getenv('DB_NAME')  # 必须从环境变量获取，不设默认

# 初始化数据库（带重试和详细日志）
def init_db():
    max_retries = 10
    retry_interval = 5
    for i in range(max_retries):
        try:
            # 打印当前连接参数（关键调试信息）
            app.logger.info(f"尝试连接数据库：host={db_host}, port={db_port}, user={db_user}, db={db_name}")
            conn = pymysql.connect(
                host=db_host,
                port=db_port,
                user=db_user,
                password=db_password,
                db=db_name
            )
            cursor = conn.cursor()
            cursor.execute('''
                CREATE TABLE IF NOT EXISTS messages (
                    id INT AUTO_INCREMENT PRIMARY KEY,
                    content TEXT NOT NULL,
                    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
                )
            ''')
            conn.commit()
            conn.close()
            app.logger.info("数据库初始化成功！")
            return
        except Exception as e:
            app.logger.error(f"第{i+1}次连接失败：{str(e)}，{retry_interval}秒后重试...")
            time.sleep(retry_interval)
    app.logger.critical("数据库连接失败，应用退出！")
    exit(1)

# 首页逻辑
@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        content = request.form.get('content')
        if content:
            try:
                conn = pymysql.connect(
                    host=db_host,
                    port=db_port,
                    user=db_user,
                    password=db_password,
                    db=db_name
                )
                cursor = conn.cursor()
                cursor.execute('INSERT INTO messages (content) VALUES (%s)', (content,))
                conn.commit()
                conn.close()
                app.logger.info(f"留言添加成功：{content}")
            except Exception as e:
                app.logger.error(f"留言添加失败：{str(e)}")
                return f"服务器错误：{str(e)}", 500
        return redirect(url_for('index'))
    
    # 读取留言
    messages = []
    try:
        conn = pymysql.connect(
            host=db_host,
            port=db_port,
            user=db_user,
            password=db_password,
            db=db_name
        )
        cursor = conn.cursor()
        cursor.execute('SELECT content, created_at FROM messages ORDER BY created_at DESC')
        messages = cursor.fetchall()
        conn.close()
    except Exception as e:
        app.logger.error(f"读取留言失败：{str(e)}")
        return f"服务器错误：{str(e)}", 500
    
    return render_template_string('''
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="UTF-8">
            <title>留言板（{{ db_name }}）</title>
        </head>
        <body>
            <h1>留言板（{{ db_name }}环境）</h1>
            <form method="POST">
                <textarea name="content" rows="3" cols="50" placeholder="请输入留言..."></textarea><br>
                <button type="submit">提交</button>
            </form>
            <hr>
            <h3>历史留言</h3>
            {% for msg in messages %}
                <p>{{ msg[1] }}：{{ msg[0] }}</p>
            {% endfor %}
        </body>
        </html>
    ''', messages=messages, db_name=db_name)

if __name__ == '__main__':
    setup_logger()
    # 启动前打印环境变量（确认配置）
    app.logger.info(f"启动参数：DB_HOST={db_host}, DB_PORT={db_port}, DB_NAME={db_name}")
    init_db()
    app.run(host='0.0.0.0', port=5000, debug=True)  # 开启调试模式
